﻿using System;

using HsTec.Mobile.Green.BLL;
using System.Web.UI.WebControls;
using HsTec.Mobile.Green.Util;
using System.IO;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.UI;
using System.Text;

public partial class DataStorage_DataStorageAnalysis : System.Web.UI.Page
{
    DataStorageBLL bll = new DataStorageBLL();
    protected void Page_Load(object sender, EventArgs e)
    {
        //if ((string)Session["Baimasoft_Pers_ID"] == null)
        //{
        //    Response.Redirect("../Logon.aspx");
        //}
        //绑定指标选项下拉框
        lstItems.Attributes.Add("onclick", "FindSelectedItems(this," + txtItems.ClientID + ");");
        if (!IsPostBack)
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = " ASC";
            }
            if (ViewState["sortExpression"] == null)
            {
                ViewState["sortExpression"] = String.Empty;
            }
            BindsltArea();
        }
    }
    protected void ddlDataTable_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue))
        {
            txtItems.Value = String.Empty;
            lstItems.Items.Clear();
            lstItems.DataSource = bll.GetItemsList(sValue);
            lstItems.DataTextField = "descript";
            lstItems.DataValueField = "colname";
            lstItems.DataBind();
        }
    }

    private string GetSearchString()
    {
        string searchStr = "(1=1)";
        string sddlRegionid = sltArea.SelectedValue.ToString().Trim();
        if (sddlRegionid != "")
        {
            searchStr += " and Area_ID  ='" + sddlRegionid + "' ";
        }
        if (this.txtSTime.Text.ToString().Trim() != "")
        {
            searchStr += " and Years >= substring(replace(convert(varchar(10),'" + this.txtSTime.Text.ToString().Trim() + "',120),'-',''),0,7) ";
        }
        if (this.txtETime.Text.ToString().Trim() != "")
        {
            searchStr += "and Years <= substring(replace(convert(varchar(10),'" + this.txtETime.Text.ToString().Trim() + "',120),'-',''),0,7) ";
        }
        return searchStr;
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue))
        {
            BindGridViewData();
            GridView1.Visible = true;
            imgReport.Visible = false;
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue) && !String.IsNullOrEmpty(HiddenID.Value))
        {
            bll.Delete(HiddenID.Value.TrimEnd(','), sValue);
            BindGridViewData();
        }
    }
    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[1].Width = 50;
        }
    }

    private void BindsltArea()
    {
        sltArea.DataTextField = "Name";
        sltArea.DataValueField = "ID";
        sltArea.DataSource = bll.GetAreaList();
        sltArea.DataBind();
        sltArea.Items.Insert(0, "请选择县市区域...");
        sltArea.Items[0].Value = "";
    }

    private void BindGridViewData()
    {
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue))
        {
            string sItems = String.Empty;
            for (int i = 0; i < lstItems.Items.Count; i++)
            {
                if (lstItems.Items[i].Selected == true)
                {
                    sItems += ",sum(" + lstItems.Items[i].Value + ") AS [" + lstItems.Items[i].Text + "]";
                }
            }
            DataView mydv = bll.GetAnalysisList(sValue, GetSearchString(), sItems);
            if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
                mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
            GridView1.DataSource = mydv;
            GridView1.DataBind();
            HiddenID.Value = "";
        }
    }
    protected void btnGraphic_Click(object sender, EventArgs e)
    {
        string sItems = String.Empty;
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue))
        {            
            for (int i = 0; i < lstItems.Items.Count; i++)
            {
                if (lstItems.Items[i].Selected == true)
                {
                    sItems += ",sum(" + lstItems.Items[i].Value + ") AS [" + lstItems.Items[i].Text + "]";
                }
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择相应的数据表！');</script>");
        }
        //输出图表
        BarChart myBc = new BarChart();

        string tmp = String.Empty;
        DataTable dt = bll.GetAnalysisList(sValue, GetSearchString(), sItems).Table;
        string imgUrl = Server.MapPath("Graphic\\Graphic") + (string)Session["Baimasoft_Pers_ID"] + ".jpg";
        if (dt.Rows.Count > 0)
        {
            tmp = dt.Rows[0]["地区"].ToString();
            myBc.ChartTitle = tmp + " " + ddlDataTable.Items[ddlDataTable.SelectedIndex].Text.Trim() + " 查询图表";
            myBc.ChartXTitle = "地区";
            myBc.ChartYTitle = "电量";
            myBc.TextValue = "地区";
            myBc.DataSource = dt;
            Bitmap img = myBc.DrawBarChart();
            img.Save(imgUrl, ImageFormat.Jpeg);
            GridView1.Visible = false;
            imgReport.Visible = true;
            Random rnd = new Random();
            imgReport.ImageUrl = "Graphic\\Graphic" + (string)Session["Baimasoft_Pers_ID"] + ".jpg?" + DateTime.Now.Millisecond + "&" + rnd.Next(100).ToString();
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('没有数据用于生成图表，请重新选择范围！');</script>");
        }
    }
    protected void btnLink_Click(object sender, EventArgs e)
    {
        string sItems = String.Empty;
        string sValue = ddlDataTable.SelectedValue.Trim();
        if (!String.IsNullOrEmpty(sValue))
        {
            for (int i = 0; i < lstItems.Items.Count; i++)
            {
                if (lstItems.Items[i].Selected == true)
                {
                    sItems += ",sum(" + lstItems.Items[i].Value + ") AS [" + lstItems.Items[i].Text + "]";
                }
            }
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择相应的数据表！');</script>");
        }
        //输出图表
        BarChart myBc = new BarChart();

        string tmp = String.Empty;
        DataTable dt = bll.GetAnalysisList(sValue, GetSearchString(), sItems).Table;
        if (dt.Rows.Count < 2)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('单条记录数据无法生成折线图，请重新选择！');</script>");
        }
        string imgUrl = Server.MapPath("Graphic\\Graphic") + (string)Session["Baimasoft_Pers_ID"] + ".jpg";
        if (dt.Rows.Count > 0)
        {
            tmp = dt.Rows[0]["地区"].ToString();
            myBc.ChartTitle = tmp + " " + ddlDataTable.Items[ddlDataTable.SelectedIndex].Text.Trim() + " 查询图表";
            myBc.ChartXTitle = "地区";
            myBc.ChartYTitle = "电量";
            myBc.TextValue = "地区";
            myBc.DataSource = dt;
            Bitmap img = myBc.DrawBrokenLine();
            img.Save(imgUrl, ImageFormat.Jpeg);
            GridView1.Visible = false;
            imgReport.Visible = true;
            Random rnd = new Random();
            imgReport.ImageUrl = "Graphic\\Graphic" + (string)Session["Baimasoft_Pers_ID"] + ".jpg?" + DateTime.Now.Millisecond + "&" + rnd.Next(100).ToString();
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('没有数据用于生成图表，请重新选择范围！');</script>");
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        try
        {
            string sValue = ddlDataTable.SelectedValue.Trim();
            HttpContext curContext = System.Web.HttpContext.Current;
            StringWriter strWriter = new StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            curContext.Response.Charset = "GB2312";
            DataView mydv = bll.GetAnalysisListExport(sValue, GetSearchString());
            if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
                mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
            GridView GV = new GridView();
            GV.DataSource = mydv;
            GV.DataBind();
            GV.RenderControl(htmlWriter);
            curContext.Response.Write(strWriter.ToString());
            curContext.Response.End();
        }
        catch
        {

        }
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sortDirection"].ToString() == " ASC")
        {
            ViewState["sortDirection"] = " DESC";
        }
        else
        {
            ViewState["sortDirection"] = " ASC";
        }
        ViewState["sortExpression"] = e.SortExpression;
        this.BindGridViewData();
    }
}
